package com.bw.services.activity

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bw.common.utils.LogUtil
import com.bw.lib_base.base.BaseActivity
import com.bw.services.R
import com.bw.services.adapter.Car_ParkingAdapter
import com.bw.services.databinding.ActivityParkingBinding
import com.bw.services.entity.CarParkingEntity
import com.bw.services.viewmodel.ServicesViewModel
import com.therouter.TheRouter
import com.therouter.router.Route
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
@Route(path = "app/ParkingActivity")
class ParkingActivity : BaseActivity<ActivityParkingBinding,ServicesViewModel>() {
    lateinit var parkingAdapter: Car_ParkingAdapter
    private val allParkingList = mutableListOf<CarParkingEntity>() // 全量数据
    private val showParkingList = mutableListOf<CarParkingEntity>() // 当前显示的数据
    private var page = 1
    private val pageSize = 10
    private var isLoading = false
    private var isLastPage = false
    override fun generatePremission(pageName: String): Array<String> {
        TODO("Not yet implemented")
    }

    override fun onResume() {
        super.onResume()
        fetchData()
    }

    override fun setupUI() {
        binding.carParking.apply {
            parkingAdapter = Car_ParkingAdapter(showParkingList)
            binding.carParking.adapter = parkingAdapter
            layoutManager = LinearLayoutManager(this@ParkingActivity)
        }
        binding.btnBack.setOnClickListener { finish() }

        // item点击事件，跳转到VrActivity
        parkingAdapter.setOnItemClickListener { position ->
            TheRouter.build("app/VrActivity").navigation()

        }
        // tv_parking_status点击事件
        parkingAdapter.setOnStatusClickListener { position, item ->
            if (item.spaceStatus == "已占用" || item.spaceStatus == "维护中") {
                val intent = Intent(this, UpDataParkingActivity::class.java)
                intent.putExtra("parkingItem", item)
                startActivity(intent)
            }
        }
        binding.btnAdd.setOnClickListener {
            TheRouter.build("app/AddParkingActivity").navigation()
        }

        // 滚动监听实现懒加载
        binding.carParking.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val layoutManager = recyclerView.layoutManager as LinearLayoutManager
                val totalItemCount = layoutManager.itemCount
                val lastVisibleItem = layoutManager.findLastVisibleItemPosition()
                if (!isLoading && !isLastPage && totalItemCount <= (lastVisibleItem + 2)) {
                    loadNextPage()
                }
            }
        })
    }

    private fun loadNextPage() {
        if (isLoading || isLastPage) return
        isLoading = true
        val from = (page - 1) * pageSize
        val to = minOf(page * pageSize, allParkingList.size)
        if (from < to) {
            showParkingList.addAll(allParkingList.subList(from, to))
            parkingAdapter.notifyDataSetChanged()
            page++
            isLastPage = to == allParkingList.size
        } else {
            isLastPage = true
        }
        isLoading = false
    }

    override fun fetchData() {
        vm.getCarParking(1)
    }

    override fun observeData() {
        lifecycleScope.launch {
            vm.carParking.collect{
                Log.d("TAG", "observeData:时代峰峻哦啊SDKif就 ")
                LogUtil.d("car_parking",it.toString())
                allParkingList.clear()
                showParkingList.clear()
                if (it != null) {
                    Log.d("TAG", "observeData:${it.size} ")
                    allParkingList.addAll(it.reversed())
                }
                page = 1
                isLastPage = false
                loadNextPage()
            }
        }
    }

    override fun handleEvent() {

    }

    override val mLayoutResId: Int
        get() = R.layout.activity_parking
}